package cn.gx.learn.security_boot_jwt_websocket.util;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedissonLockUtil {

    @Autowired
    private RedissonClient redissonClient;

    public boolean trylock(String lock, long wattime, long leasetime, TimeUnit timeunit){

        try {
            RLock rLock = redissonClient.getLock(lock);
            return rLock.tryLock(wattime,leasetime,timeunit);
        }catch (InterruptedException e){
            Thread.currentThread().interrupt();
            return false;
        }

    }

    public boolean unlock(String lock){
        try {
            RLock rLock = redissonClient.getLock(lock);
            if(rLock.isHeldByCurrentThread()){
                rLock.unlock();
                return true;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return false;

    }






}
